<?php

namespace App\Http\Controllers\Manage;

use App\Model\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Manage;
use Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Validator;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $role_id = session('user.role_id');
        $id = $request->session()->get('user.id');

        $obj = new Manage;
        $check_time = Input::get('check_time');
        $category = Input::get('category');
        $keyword = Input::get('keyword');
        $time = Input::get('create_time');
        $type = Input::get('type');
        $code = Input::get('code');
        if(Input::has('category') && Input::has('keyword')) {
            if(Input::get('category') === 'create_user' || Input::get('category') === 'update_user') {
                $user = Manage::select('id')->where('username','like',"%$keyword%")->get();
                $obj = $obj->whereIn(Input::get('category'),$user);
            }
            else if(Input::get('category') === 'role_id') {
                $role = Role::selsect('id')->where('name','like',"%$keyword%")->get();
                $obj = $obj->whereIn('role_id',$role);
            }
            else {
                $obj = $obj->where(Input::get('category'),'like',"%$keyword%");
            }
        }
        if(Input::has('check_time')) {
            $start_time = date("Y-m-d 00:00:00",strtotime(substr($time , 0 , 10)));
            $end_time = date("Y-m-d 23:59:59",strtotime(substr($time,-10)));
            $obj = $obj->whereBetween('create_time',[$start_time,$end_time]);
        }
        //升降排序
        if(Input::has('type') && Input::has('code')) {
            if($code == 0) {
                $obj = $obj->orderBy($type,'asc');
            }
            if($code == 1) {
                $obj = $obj->orderBy($type,'desc');
            }
        }
        #页面检测是否分页
        $isPage = '';
        if($role_id == 1){
            $data = $obj->paginate(10);
            $isPage = 1;
        }else{
            $data = $obj->where('id', $id)->get();
        }
        $field = Manage::getField();
        return view('manage/system/user/index', compact('title', 'data','field','check_time','category','keyword','time','type','code'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //获取角色信息
        $role = Role::where('status',1)->get();
        return view('manage.system.user.create',compact('role'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $input = $request->only('user_id','role_id','username', 'email', 'password');
        $rule = [
            'role_id' => 'required',
            'username' => 'required',
            'password' => 'required|min:5',
        ];
        $message = [
            'required' => ':attribute 不能为空'
        ];
        $attributes = [
            'role_id' => '角色',
            'username' => '用户名',
            'password' => '密码',
        ];
        $validator = Validator::make($input, $rule, $message, $attributes);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }else{
            #查找重复
            if(Manage::where('username',$request['username'])->first()){
                return redirect()->back()->withInput()->withErrors('用户名已被注册！');
            }
            $res = Manage::insert([
                'create_user' => $request->input('user_id'),
                'role_id'=>$request->input('role_id'),
                'username'=>$request->input('username'),
                'email'=>$request->input('email'),
                'password'=>Hash::make($request->input('password')),
            ]);
            if($res){
                return Redirect::to("manage/user");
            }else{
                return redirect()->back()->withInput()->withErrors('创建失败！');
            }
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        #获取该用户信息
        $user = Manage::where('id', $id)->first();
        #获取所有角色信息
        $role = Role::where('status',1)->get();
        return view('manage/system/user/edit', compact('user','role'));

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $input = $request->only('user_id','role_id','username','email', 'password');
        $callback = null;
        $rule = [
            'role_id' => 'required',
            'username' => 'required',
//            'password' => 'min:5',
        ];
        $message = [
            'role_id.required' => '角色不能为空',
            'username.required' => '用户名不能为空',
            'email.email' => '邮箱格式错误',
//            'password.required' => '密码不能为空',
            'password.min' => '密码至少需要5位长度',
        ];
        $validator = Validator::make($input, $rule, $message);
        if($validator->fails()) {
//            $warnings = $validator->messages();
//            $ShowWarnings = $warnings->first();
//            $callback = [
//                'msg' => $ShowWarnings
//            ];
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }
        else {
            $result = Manage::where('id', $id)->first();
            if($result->email == $request->input('email') && Hash::check($request->input('password'), $result->password)) {
//                $callback = [
//                    'msg' => '用户名密码均无变化'
//                ];
                return redirect()->back()->withInput()->withErrors('用户名密码均无变化');
            }
            else {
                if($result->email != $request->input('email') ) {
                    $result->email = $request->input('email');
                }
                if($result->role_id != $request->input('role_id') ) {
                    $result->role_id = $request->input('role_id');
                }
                if($result->username != $request->input('username') ) {
                    $result->username = $request->input('username');
                }
                if(!Hash::check($request->input('password'), $result->password) && !empty($request->input('password'))) {
                    $result->password = Hash::make($request->input('password'));
                }
                $result->update_user = $request->input('user_id');
                $result->save();
//                $callback = [
//                    'code' => 100,
//                    'msg' => '更新成功！'
//                ];
                return redirect()->back()->withInput()->with('success','修改成功！');
            }
        }
//        return json_encode($callback);

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return array
     */
    public function destroy()
    {
        $id = Input::get('id');
        $res = Manage::where('id',$id)->delete();
        if($res){
            return [
                'code' => 100,
                'msg' => '删除成功！'
            ];
        }else{
            return [
                'code' => 101,
                'msg' => '删除失败！'
            ];
        }
    }

    /**
     * 修改管理员状态
     * @return array
     */
    public function setStatus()
    {
        $id = Input::get('id');
        $status = Input::get('status');
        if($status == 1) {
            $del = Manage::where('id',$id)->update(['status'=>1,'update_user'=>session('user.id')]);
            $msg = '启用成功！';
        }else{
            $del = Manage::where('id',$id)->update(['status'=>0,'update_user'=>session('user.id')]);
            $msg = '禁用成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

    /*
     * 修改密码
     */
    public function password() {
        return view('manage/system/user/password');
    }

    /*
     * 更新密码
     */
    public function change_pass(Request $request) {

        $input = $request->only('old_pass','new_pass','dob_pass','user_id');
        $callback = null;
        $rule = [
            'old_pass' => 'required',
            'new_pass' => 'required',
            'dob_pass' => 'required',
        ];
        $message = [
            'old_pass.required' => '旧密码不能为空',
            'new_pass.required' => '新密码不能为空',
            'dob_pass.required' => '确认密码不能为空',

        ];
        $validator = Validator::make($input, $rule, $message);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }
        else {
            $old = Manage::where('id',$request->input('user_id'))->first();
            if(Hash::check($input['old_pass'], $old->password)) {
                if($request->input('new_pass') == $request->input('dob_pass')) {
                    $map = Manage::where('id',$request->input('user_id'))->update(['update_user'=>$request->input('user_id'),'password'=>Hash::make($request->input('new_pass'))]);
                    if($map) {
                        return redirect()->back()->withInput()->with('success','修改成功！');
                    }
                    else {
                        return redirect()->back()->withInput()->withErrors('修改失败!');
                    }
                }
                else {
                    return redirect()->back()->withInput()->withErrors('新密码两次不一致!');
                }
            }
            else {
                return redirect()->back()->withInput()->withErrors('旧密码错误!');
            }
        }
    }
}
